package com.yiyihealth.cherriesadmin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.*;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yiyihealth.cherriesadmin.config.RunEnvironment;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.quartz.QuartzUtil;
import com.yiyihealth.cherriesadmin.core.service.impl.BaseServiceImpl;
import com.yiyihealth.cherriesadmin.core.smsInterface.AliyunSmsUtil;
import com.yiyihealth.cherriesadmin.core.utils.JKTUtil;
import com.yiyihealth.cherriesadmin.core.webservice.MainServiceImplPortType;
import com.yiyihealth.cherriesadmin.mapper.*;
import com.yiyihealth.cherriesadmin.model.*;
import com.yiyihealth.cherriesadmin.model.his.ExecutionResult;
import com.yiyihealth.cherriesadmin.model.his.OutRegisterNet;
import com.yiyihealth.cherriesadmin.model.jkt.JThealth;
import com.yiyihealth.cherriesadmin.model.jkt.JktFunc10007;
import com.yiyihealth.cherriesadmin.model.jkt.JktFunc10008;
import com.yiyihealth.cherriesadmin.model.jkt.JktFunc10009;
import com.yiyihealth.cherriesadmin.model.wrapper.OrdAppointmentWrapper;
import com.yiyihealth.cherriesadmin.service.OrdAppointmentService;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.chrono.ChronoLocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

import static com.yiyihealth.cherriesadmin.core.utils.JKTUtil.sortMap;

/**
 * 预约订单记录(OrdAppointment)表服务实现类
 *
 * @author chen
 * @since 2020-09-14 20:03:29
 */
@CacheConfig(cacheNames = "appointment")
@Transactional(isolation = Isolation.SERIALIZABLE)
@Service("ordAppointmentService")
public class OrdAppointmentServiceImpl extends BaseServiceImpl<OrdAppointment, OrdAppointmentWrapper, Long> implements OrdAppointmentService {
    @Resource
    private OrdAppointmentMapper ordAppointmentMapper;
    @Resource
    private OrdSourceDetailMapper sourceDetailMapper;
    @Resource
    private OrdSchedulingMapper schedulingMapper;
    @Resource
    private PubHospitalMapper hospitalMapper;
    @Resource
    private PubSuffererMapper suffererMapper;
    @Resource
    private OrdSchedulingTemplateMapper ordSchedulingTemplateMapper;
    @Resource
    private OrdSchedulingHistoryMapper  schedulingHistoryMapper;
    @Resource
    private RedisTemplate<Object, Object> redisCacheTemplate;
    @Resource
    private JktFunc10008 jktFunc10008;
    @Resource
    private JktFunc10009 jktFunc10009;
    @Resource
    private JThealth jThealth;
    @Resource
    private RunEnvironment runEnvironment;

    @Resource
    private  PubDepartmentsMapper PubDepartmentsMapper;

    @Resource
    private  PubDoctorMapper PubDoctorMapper;
    @Autowired
    private void setEntityMapper() {
        super.setEntityMapper(ordAppointmentMapper);
    }

    @Override
    public List<OrdAppointment> selectList(Map<String, Object> map) {
        List<OrdAppointment> ordAppointmentList =  ordAppointmentMapper.selectList(map);
        ordAppointmentList.forEach(ordAppointment -> {
            if (!StrUtil.isBlank(ordAppointment.getPatIdentityNum())){
                ordAppointment.setAge(IdcardUtil.getAgeByIdCard(ordAppointment.getPatIdentityNum())+"");
            }
        });
        return ordAppointmentList;
    }


    @Override
    public OrdAppointment selectByPrimaryKeypat(Long id) {
        return ordAppointmentMapper.selectByPrimaryKeypat(id);
    }


    /**
     * 后台取消预约
     * @param record
     * @return
     * @throws Exception
     */
    @Override
    public String cancelByBack(OrdAppointment record) throws Exception {
        //预约状态(0已预约 1已过期 2已取号 3患者取消 4医生停诊 5后台取消)
        record.setAppStatus(5);
        record.setCancelDate(LocalDateTime.now());
        ordAppointmentMapper.updateByPrimaryKeySelective(record);
        OrdSourceDetail sourceDetail = sourceDetailMapper.selectByPrimaryKey(record.getSourceDetailId());
        sourceDetail.setStatus("0");
        //使用状态(1窗口挂号 2平台预约取号 3平台爽约 4院内预约取号 5院内爽约 6退号 7医生停诊)
        sourceDetail.setState("6");
        sourceDetailMapper.updateByPrimaryKeySelective(sourceDetail);
        OrdScheduling scheduling=schedulingMapper.selectByPrimaryKey(record.getSchedulingId());
        scheduling.setAmountSurplus(scheduling.getAmountSurplus() + 1);
        schedulingMapper.updateByPrimaryKeySelective(scheduling);
        //调用HIS接口推送数据到HIS
        String result="";
        if (runEnvironment.getActive().equals("dev")){
            //十五分内随机释放号源
            String sourceDetailKey="sourceDetail:"+record.getDoctorId()+":"+record.getSchedulingId();
            String schedulingKey="scheduling:"+record.getDoctorId()+":"+record.getSchedulingId();
            Integer interval = QuartzUtil.redisCacheTask(schedulingKey,sourceDetailKey,record.getSourceDetailId().toString(),record.getId().toString());
            result = "第"+record.getSerialNumber()+"号将于"+interval+"分钟后释放号源";
            if (!record.getSpName().equals("jkt")){
                JKTUtil.jktFunc10009App(jktFunc10009,jThealth,record);
            }
        }else {
            ExecutionResult executionResult = deleteDataHIS(record);
            if (executionResult.getOutResult().equals(0)){
                PubHospital hospital = hospitalMapper.selectByPrimaryKey(record.getHospitalId());
                if (!record.getSpName().equals("jkt")){
                    JKTUtil.jktFunc10009App(jktFunc10009,jThealth,record);
                }
                JSONObject cancelAppointmentReminder = new JSONObject();
                //取消预约---您好${patName},您预约${hosName}医院${date}日的${depName}门诊${doctorName}医生${ampm}第${serialNumber}号已被取消。咨询电话：${phone}。
                cancelAppointmentReminder.set("patName",record.getPatName());
                cancelAppointmentReminder.set("hosName",hospital.getHosName());
                cancelAppointmentReminder.set("date",LocalDateTimeUtil.format(record.getVisitDate(), DatePattern.CHINESE_DATE_PATTERN));
                cancelAppointmentReminder.set("ampm",scheduling.getTimeState().equals(1) ? "上午" : scheduling.getTimeState().equals(2) ? "下午" : "夜门诊");
                cancelAppointmentReminder.set("depName",record.getDepName());
                cancelAppointmentReminder.set("doctorName",record.getDoctorName());
                cancelAppointmentReminder.set("serialNumber",record.getSerialNumber());
                cancelAppointmentReminder.set("phone",hospital.getHosPhone());
                AliyunSmsUtil.sendSms(record.getPhone(),"SMS_206536212",cancelAppointmentReminder.toString());
                //十五分内随机释放号源
                String sourceDetailKey="sourceDetail:"+record.getDoctorId()+":"+record.getSchedulingId();
                String schedulingKey="scheduling:"+record.getDoctorId()+":"+record.getSchedulingId();
                Integer interval = QuartzUtil.redisCacheTask(schedulingKey,sourceDetailKey,record.getSourceDetailId().toString(),record.getId().toString());
                result = "第"+record.getSerialNumber()+"号将于"+interval+"分钟后释放号源";

            }else {
                result = executionResult.getOutData();
            }
        }
        return  result;
    }

    /**
     * 后台预约
     * @param record
     * @return
     */
    @Override
    public synchronized String createByBack(OrdAppointment record) throws Exception {
        String sourceDetailKey="sourceDetail:"+record.getDoctorId()+":"+record.getSchedulingId();
        OrdSourceDetail sourceDetail = sourceDetailMapper.selectByPrimaryKey(record.getSourceDetailId());
        if (sourceDetail.getStatus().equals("1")){
            JKTUtil.jktFunc10009Sou(jktFunc10009,jThealth,sourceDetail);
            throw new Exception("此号已被预约，请选择其他号段！");
        }
        if (!redisCacheTemplate.opsForSet().isMember(sourceDetailKey,record.getSourceDetailId())){
            JKTUtil.jktFunc10009Sou(jktFunc10009,jThealth,sourceDetail);
            throw new Exception("号源池未释放，请选择其他号段！");
        }
        if (Optional.ofNullable(record.getPatIdentityNum()).isPresent() && IdcardUtil.isValidCard(record.getPatIdentityNum())){
            String sex = IdcardUtil.getGenderByIdCard(record.getPatIdentityNum())+"";
            if (!record.getPatSex().equals(sex)){
                throw new Exception("所选性别与身份证不匹配！");
            }
        }
        record.setCreateDate(LocalDate.now());
        record.setPassword(RandomUtil.randomNumbers(8));
        if (!Optional.ofNullable(record.getSpName()).isPresent()){
            record.setSpName("后台预约");
        }


        sourceDetail.setStatus("1");
        //使用状态(1窗口挂号 2平台预约取号 3平台爽约 4院内预约取号 5院内爽约 6退号 7医生停诊)
        sourceDetail.setState("7");
        PubHospital hospital = hospitalMapper.selectByPrimaryKey(sourceDetail.getHospitalId());
        record.setHospitalId(hospital.getId());
        ordAppointmentMapper.insert(record);
        OrdScheduling scheduling=schedulingMapper.selectByPrimaryKey(record.getSchedulingId());
        sourceDetailMapper.updateByPrimaryKeySelective(sourceDetail);
        scheduling.setAmountSurplus(scheduling.getAmountSurplus() - 1);
        schedulingMapper.updateByPrimaryKeySelective(scheduling);

        //调用HIS接口推送数据到HIS
        PubSufferer sufferer = suffererMapper.selectByPrimaryKey(record.getPatId());
        sufferer.setHospitalId(record.getHospitalId());
        String result="";
        if (runEnvironment.getActive().equals("dev")){
            if (!record.getSpName().equals("jkt")){
                JKTUtil.jktFunc10009App(jktFunc10009,jThealth,record);
            }
        }else {
            ExecutionResult executionResult = storedProcedure(sufferer);
            executionResult = pushDataHIS(record);

            if (executionResult.getOutResult().equals(0)){
                String schedulingKey="scheduling:"+record.getDoctorId()+":"+record.getSchedulingId();
                try {
                    if (redisCacheTemplate.opsForSet().isMember(sourceDetailKey,record.getSourceDetailId())){
                        redisCacheTemplate.opsForValue().decrement(schedulingKey,1);
                        redisCacheTemplate.opsForSet().remove(sourceDetailKey,record.getSourceDetailId());
                    }else {
                        if (!record.getSpName().equals("jkt")){
                            JKTUtil.jktFunc10009Sou(jktFunc10009,jThealth,sourceDetail);
                        }
                        throw new Exception("此号已被预约，请重新选择！");
                    }
                    if (!record.getSpName().equals("jkt")){
                        JKTUtil.jktFunc10009App(jktFunc10009,jThealth,record);
                    }
                }catch (Exception e){
                    throw new Exception(e.getMessage());
                }
            }else {
                result = executionResult.getOutData();
            }
        }
        return  result;
    }

    /**
     * H5页面预约
     * @param record
     * @param sourceDetailId
     * @return
     * @throws Exception
     */
    @Override
    public synchronized String createByPatIdSourceDetailId(OrdAppointment record, Long sourceDetailId) throws Exception {
        OrdSourceDetail sourceDetail = sourceDetailMapper.selectByPrimaryKey(sourceDetailId);
        String schedulingKey="scheduling:"+sourceDetail.getDoctorId()+":"+sourceDetail.getSchedulingId();
        String sourceDetailKey="sourceDetail:"+sourceDetail.getDoctorId()+":"+sourceDetail.getSchedulingId();
        if (!redisCacheTemplate.opsForSet().isMember(sourceDetailKey,sourceDetail.getId())){
            JKTUtil.jktFunc10009Sou(jktFunc10009,jThealth,sourceDetail);
            throw new Exception("此号已被预约，请选择其他号源！");
        }
        record.setSchedulingId(sourceDetail.getSchedulingId());
        record.setSourceDetailId(sourceDetail.getId());
        record.setSerialNumber(sourceDetail.getSerialNumber());
        record.setPassword(RandomUtil.randomNumbers(8));
        record.setDepId(sourceDetail.getDepId());
        record.setDepName(sourceDetail.getDepName());
        record.setDoctorId(sourceDetail.getDoctorId());
        record.setDoctorName(sourceDetail.getDoctorName());
        record.setBinId(sourceDetail.getBinId());
        record.setBinName(sourceDetail.getBinName());
        record.setAppType("0");
        record.setAppStatus(0);
        record.setVisitTime(sourceDetail.getVisitTime());
        record.setHospitalId(sourceDetail.getHospitalId());
        record.setVisitDate(sourceDetail.getSchedulingDate());
        record.setTimeState(sourceDetail.getTimeState());
        PubHospital hospital = hospitalMapper.selectByPrimaryKey(sourceDetail.getHospitalId());
        if (!Optional.ofNullable(hospital).isPresent()){
            hospital = hospitalMapper.selectByPrimaryKey(20L);
        }
        ordAppointmentMapper.insert(record);
        sourceDetail.setStatus("1");
        //使用状态(1窗口挂号 2平台预约取号 3平台爽约 4院内预约 5院内爽约 6退号 7医生停诊)
        sourceDetail.setState("4");
        sourceDetailMapper.updateByPrimaryKeySelective(sourceDetail);
        OrdScheduling scheduling=schedulingMapper.selectByPrimaryKey(record.getSchedulingId());
        scheduling.setAmountSurplus(scheduling.getAmountSurplus() - 1);
        schedulingMapper.updateByPrimaryKeySelective(scheduling);

        //调用HIS接口推送数据到HIS
        PubSufferer sufferer = suffererMapper.selectByPrimaryKey(record.getPatId());
        sufferer.setHospitalId(record.getHospitalId());
        String result="";
        if (runEnvironment.getActive().equals("dev")) {
            JKTUtil.jktFunc10009App(jktFunc10009, jThealth, record);
        }else {
            ExecutionResult executionResult = storedProcedure(sufferer);
            executionResult = pushDataHIS(record);
            if (executionResult.getOutResult().equals(0)){
                if (Optional.ofNullable(record).isPresent()){
                    try {
                        if (redisCacheTemplate.opsForSet().isMember(sourceDetailKey,record.getSourceDetailId())){
                            redisCacheTemplate.opsForValue().decrement(schedulingKey,1);
                            redisCacheTemplate.opsForSet().remove(sourceDetailKey,record.getSourceDetailId());
                        }else {
                            JKTUtil.jktFunc10009Sou(jktFunc10009, jThealth, sourceDetail);
                            throw new Exception("此号已被预约，请重新选择！");
                        }
                        JKTUtil.jktFunc10009App(jktFunc10009,jThealth,record);
                    }catch (Exception e){
                        throw new Exception(e.getMessage());
                    }
                }
                result = "预约成功 第"+record.getSerialNumber()+"号";
            }else {
                result = executionResult.getOutData();
            }
        }
        return  result;
    }

    /**
     * H5取消预约
     * @param appointment
     * @return
     * @throws Exception
     */
    @Override
    public String delete(OrdAppointment appointment) throws Exception {
        OrdSourceDetail sourceDetail=sourceDetailMapper.selectByPrimaryKey(appointment.getSourceDetailId());
        OrdScheduling scheduling=schedulingMapper.selectByPrimaryKey(appointment.getSchedulingId());
        //预约状态(0已预约 1已过期 2已取号 3患者取消 4医生停诊 5后台取消)
        if (appointment.getAppStatus().equals(3)){
            appointment.setAppStatus(0);
            appointment.setCancelDate(null);
            sourceDetail.setStatus("1");
            //使用状态(1窗口挂号 2平台预约取号 3平台爽约 4院内预约取号 5院内爽约 6退号 7医生停诊)
            sourceDetail.setState("1");
        }else {
            appointment.setAppStatus(3);
            appointment.setCancelDate(LocalDateTime.now());
            sourceDetail.setStatus("0");
            //使用状态(1窗口挂号 2平台预约取号 3平台爽约 4院内预约取号 5院内爽约 6退号 7医生停诊)
            sourceDetail.setState("0");
            scheduling.setAmountSurplus(scheduling.getAmountSurplus() + 1);
        }
        sourceDetailMapper.updateByPrimaryKeySelective(sourceDetail);
        schedulingMapper.updateByPrimaryKeySelective(scheduling);
        ordAppointmentMapper.updateByPrimaryKeySelective(appointment);

        //调用HIS接口推送数据到HIS
        ExecutionResult executionResult = deleteDataHIS(appointment);
        String result="";
        if (!appointment.getSpName().equals("jkt")){
            JKTUtil.jktFunc10009App(jktFunc10009,jThealth,appointment);
        }
        if (executionResult.getOutResult().equals(0)){
            PubHospital hospital = hospitalMapper.selectByPrimaryKey(appointment.getHospitalId());
            JSONObject cancelAppointmentReminder = new JSONObject();
            //取消预约---您好${patName},您预约${hosName}医院${date}日的${depName}门诊${doctorName}医生${ampm}第${serialNumber}号已被取消。咨询电话：${phone}。
            cancelAppointmentReminder.set("patName",appointment.getPatName());
            cancelAppointmentReminder.set("hosName",hospital.getHosName());
            cancelAppointmentReminder.set("date",LocalDateTimeUtil.format(appointment.getVisitDate(), DatePattern.CHINESE_DATE_PATTERN));
            cancelAppointmentReminder.set("ampm",scheduling.getTimeState().equals(1) ? "上午" : scheduling.getTimeState().equals(2) ? "下午" : "夜门诊");
            cancelAppointmentReminder.set("depName",appointment.getDepName());
            cancelAppointmentReminder.set("doctorName",appointment.getDoctorName());
            cancelAppointmentReminder.set("serialNumber",appointment.getSerialNumber());
            cancelAppointmentReminder.set("phone",hospital.getHosPhone());
            AliyunSmsUtil.sendSms(appointment.getPhone(),"SMS_206536212",cancelAppointmentReminder.toString());
            //十五分内随机释放号源
            String sourceDetailKey="sourceDetail:"+appointment.getDoctorId()+":"+appointment.getSchedulingId();
            String schedulingKey="scheduling:"+appointment.getDoctorId()+":"+appointment.getSchedulingId();
            Integer interval = QuartzUtil.redisCacheTask(schedulingKey,sourceDetailKey,appointment.getSourceDetailId().toString(),appointment.getId().toString());
            result = "第"+appointment.getSerialNumber()+"号将于"+interval+"分钟后释放号源";
        }else {
            result = executionResult.getOutData();
        }

        return  result;
    }

    /**
     *
     * @throws Exception
     */
    @Override
    public void extractHisData() throws Exception {

    }

    /**
     * 上传就诊信息功能说明：
     * 对于通过网上预约的患者， 医院需要在就诊日当天晚上上传当日所有预约用户的就诊情况， 只需要上传从省平台预约的患者就诊信息即可
     * 每天23点上传当天及其以前的平台预约就诊情况
     */
    @Scheduled(cron = "0 23 23 ? * *")
    @Override
    public synchronized void uploadVisitInformation() throws Exception {
        Map<String, Object> sMap = new HashMap<>(16);
        sMap.put("visitDate", LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE));
        //所有当日未取号记录
        List<OrdAppointment> appointmentsList = ordAppointmentMapper.selectList(sMap);
        for (OrdAppointment appointment:appointmentsList){
            //同步预约取号状态
            PubHospital hospital = hospitalMapper.selectByPrimaryKey(appointment.getHospitalId());
            if (StrUtil.isBlank(hospital.getHosRegionalCode())){
                continue;
            }
            String tokenStr = "";
            sMap.clear();
            sMap.put("userid",appointment.getPatId());
            sMap.put("passwd",appointment.getPassword());
            String json = JSONUtil.parse(sMap).toString();
            try {
                tokenStr = HttpUtil.post(hospital.getHosRegionalCode()+"/outRegisterNet/select_list", json);
            } catch (Exception e) {
                throw new Exception("调用"+ hospital.getHosName()+"中间数据处理服务失败,请确认服务地址："+hospital.getHosRegionalCode()+"是否正常！");
            }
            HttpResult httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
            List<OutRegisterNet> outRegisterNetList = JSONUtil.toList((JSONArray) httpResult.getData(),OutRegisterNet.class);
            if (!CollectionUtils.isEmpty(outRegisterNetList)){
                OutRegisterNet registerNet = outRegisterNetList.get(0);
                if (Optional.ofNullable(registerNet.getConfigflag()).isPresent()){
                    if (registerNet.getConfigflag().equals(1)){
                        //设置已取号状态
                        appointment.setAppStatus(2);
                    }
                }
            }
            //当天未取号则 设置为违约
            if (appointment.getAppStatus().equals(0)){
                appointment.setAppStatus(1);
                //12580预约未取号则 设置状态 未取号不违约
                if (Optional.ofNullable(appointment.getCardType()).isPresent()){
                    if (appointment.getCardType().equals("1")){
                        appointment.setTakeCode("3");
                    }
                }

            }
            ordAppointmentMapper.updateByPrimaryKeySelective(appointment);
        }

        sMap.clear();
        sMap.put("visitDate", LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE));
        sMap.put("cardType","0");
        List<OrdAppointment> appointments = ordAppointmentMapper.selectList(sMap);
        for (OrdAppointment appointment:appointments){
            PubHospital hospital = hospitalMapper.selectByPrimaryKey(appointment.getHospitalId());
            AppointmentFunMain(hospital,appointment);
        }
    }

    /**
     * 根预约就诊t+1日凌晨2:00-4:00前结束
     */
    @Scheduled(cron = "0 23 3 ? * *")
    @Override
    public synchronized void jktUploadVisitInformation() throws Exception {
        Map<String, Object> sMap = new HashMap<>(16);
        sMap.put("visitDate", LocalDateTimeUtil.format(LocalDate.now().minusDays(1),"yyyy-MM-dd"));
        sMap.put("spName","jkt");
        List<OrdAppointment> appointments = ordAppointmentMapper.selectList(sMap);
        for (OrdAppointment appointment:appointments){
            jktFunc10008.setOrderId(appointment.getId().toString());
            jktFunc10008.setRegId(appointment.getId().toString());
            jktFunc10008.setRegPassword(appointment.getPassword());
            jktFunc10008.setMedDate(LocalDateTimeUtil.format(appointment.getVisitDate(),"yyyyMMdd"));
            jktFunc10008.setMedStatus(appointment.getAppStatus().toString());

            List<JSON> jktFun10008InList = new ArrayList<>();
            sortMap(BeanUtil.beanToMap(jktFunc10008));
            jktFun10008InList.add(JSONUtil.parse(jktFunc10008));
            Map<String,Object> FuncMap =  new HashMap<>();
            FuncMap.put("list",jktFun10008InList);
            JKTUtil.jThealthPost("10008",FuncMap, jThealth);
        }
    }


    /**
     * H5根据用户信息查询预约记录
     * @param patId
     * @return
     */
    @Override
    public List<OrdAppointmentWrapper> selectListByPatId(Long patId) {
        Map<String, Object> sMap = new HashMap<>(16);
        sMap.put("patId", patId);
        List<PubSufferer> pubSuffererList = suffererMapper.selectList(sMap);
        List<OrdAppointmentWrapper> appointmentList = new ArrayList<>();
        for (PubSufferer pubSufferer:pubSuffererList){
            sMap.put("patId", pubSufferer.getId());
            List<OrdAppointmentWrapper> appointments = ordAppointmentMapper.selectListWrapper(sMap);
            appointmentList.addAll(appointments);
        }

        for (OrdAppointmentWrapper appointment:appointmentList){
            int week = appointment.getVisitDate().getDayOfWeek().getValue()+1>7?1:appointment.getVisitDate().getDayOfWeek().getValue()+1;
            PubHospital hospital = hospitalMapper.selectByPrimaryKey(appointment.getHospitalId());
            appointment.setHospitalIdWrapper(hospital.getHosShortName());
            appointment.setWeekWrapper(Week.of(week).toChinese());
            //预约状态(0已预约 1已过期 2已取号 3患者取消 4医生停诊 5后台取消)
            if (appointment.getAppStatus().equals(0)){
                appointment.setAppStatusWrapper("待取号");
            }else  if (appointment.getAppStatus().equals(1)){
                appointment.setAppStatusWrapper("已过期");
            }else  if (appointment.getAppStatus().equals(2)){
                appointment.setAppStatusWrapper("已取号");
            }else  if (appointment.getAppStatus().equals(3)){
                appointment.setAppStatusWrapper("患者取消");
            }else  if (appointment.getAppStatus().equals(4)){
                appointment.setAppStatusWrapper("医生停诊");
            }else  if (appointment.getAppStatus().equals(5)){
                appointment.setAppStatusWrapper("平台取消");
            }
            appointment.setTimeStateWrapper(appointment.getTimeState().equals(1) ? "上午" : appointment.getTimeState().equals(2) ? "下午" : "夜门诊");
        }
        appointmentList = appointmentList.stream().sorted(Comparator.comparing(OrdAppointment::getVisitDate).reversed()).collect(Collectors.toList());
        appointmentList = appointmentList.stream().sorted(Comparator.comparing(OrdAppointment::getAppStatus)).collect(Collectors.toList());
        return appointmentList;
    }

    @Override
    public List<OrdAppointmentWrapper> selectListBySufferId(Long patId) {
        Map<String, Object> sMap = new HashMap<>(16);
        sMap.put("patId", patId);
        List<OrdAppointmentWrapper> appointmentList = ordAppointmentMapper.selectListWrapper(sMap);

        for (OrdAppointmentWrapper appointment:appointmentList){
            int week = appointment.getVisitDate().getDayOfWeek().getValue()+1>7?1:appointment.getVisitDate().getDayOfWeek().getValue()+1;
            PubHospital hospital = hospitalMapper.selectByPrimaryKey(appointment.getHospitalId());
            appointment.setHospitalIdWrapper(hospital.getHosShortName());
            appointment.setWeekWrapper(Week.of(week).toChinese());
            //预约状态(0已预约 1已过期 2已取号 3患者取消 4医生停诊 5后台取消)
            if (appointment.getAppStatus().equals(0)){
                appointment.setAppStatusWrapper("待取号");
            }else  if (appointment.getAppStatus().equals(1)){
                appointment.setAppStatusWrapper("已过期");
            }else  if (appointment.getAppStatus().equals(2)){
                appointment.setAppStatusWrapper("已取号");
            }else  if (appointment.getAppStatus().equals(3)){
                appointment.setAppStatusWrapper("患者取消");
            }else  if (appointment.getAppStatus().equals(4)){
                appointment.setAppStatusWrapper("医生停诊");
            }else  if (appointment.getAppStatus().equals(5)){
                appointment.setAppStatusWrapper("平台取消");
            }
            appointment.setTimeStateWrapper(appointment.getTimeState().equals(1) ? "上午" : appointment.getTimeState().equals(2) ? "下午" : "夜门诊");
        }
        appointmentList = appointmentList.stream().sorted(Comparator.comparing(OrdAppointment::getVisitDate).reversed()).collect(Collectors.toList());
        appointmentList = appointmentList.stream().sorted(Comparator.comparing(OrdAppointment::getAppStatus)).collect(Collectors.toList());
        return appointmentList;
    }


    @Override
    public List selectStatis(Map map) {

        List<OrdAppointment> list=ordAppointmentMapper.selectList(map);
        List list1=new ArrayList();
        Integer num=0;
        long[] l=new long[3];
        l[0]=57170;
        l[1]=57171;
        l[2]=57172;
        for(int i=6;i>=0;i--){
            LocalDate end = LocalDate.now().minusMonths(i);

            LocalDate firstday = LocalDate.of(end.getYear(), end.getMonthValue(), 1);
            LocalDate firstday2=firstday.plusDays(-1);

            LocalDate lastMonthDay = end.with(TemporalAdjusters.lastDayOfMonth());
            LocalDate lastMonthDay2=lastMonthDay.plusDays(1);
          for (int k=0;k<l.length;k++){
              for (int j=0;j<list.size();j++){
                  if (firstday2.isBefore(ChronoLocalDate.from(list.get(j).getCreateDate()))&&lastMonthDay2.isAfter(ChronoLocalDate.from(list.get(j).getCreateDate()))&&list.get(j).getHospitalId()==l[k]){
                       num++;
                  }
              }
              statis statis=new statis();
              statis.setHisID(l[k]);
              statis.setDate(firstday);
              statis.setNum(num);
              list1.add(statis);
              num=0;
          }
        }


        return list1;
    }

    @Override
    public List priselectStatis(Map map) {
        List<OrdAppointment> list=ordAppointmentMapper.selectList(map);
        List list1=new ArrayList();
        Integer num=0;
        long[] l=new long[3];
        l[0]=57170;
        l[1]=57171;
        l[2]=57172;
        for(int i=6;i>=0;i--){
            LocalDate end = LocalDate.now().minusMonths(i);

            LocalDate firstday = LocalDate.of(end.getYear(), end.getMonthValue(), 1);
            LocalDate firstday2=firstday.plusDays(-1);

            LocalDate lastMonthDay = end.with(TemporalAdjusters.lastDayOfMonth());
            LocalDate lastMonthDay2=lastMonthDay.plusDays(1);
            for (int k=0;k<l.length;k++){
                for (int j=0;j<list.size();j++){
                    if (firstday2.isBefore(ChronoLocalDate.from(list.get(j).getCreateDate()))&&lastMonthDay2.isAfter(ChronoLocalDate.from(list.get(j).getCreateDate()))&&list.get(j).getHospitalId()==l[k]&&list.get(j).getSpName().equals("")){
                        num++;
                    }
                }
                statis statis=new statis();
                statis.setHisID(l[k]);
                statis.setDate(firstday);
                statis.setNum(num);
                list1.add(statis);
                num=0;
            }
        }


        return list1;
    }
    @Override
    public List selectStatisDoctor(Map map) {
        System.out.println(map);
        List list1=new ArrayList();
        List<OrdAppointment> list=ordAppointmentMapper.selectList(map);
        List<PubDoctor> Doctorlist=PubDoctorMapper.selectList(map);
        List<PubDoctor> Doctorlist2=new ArrayList<>();
        LocalDate date=LocalDate.now();
        Integer num=0;
        for (int i=0;i<Doctorlist.size();i++){
           if (Doctorlist.get(i).getStatus().equals("0")){
               PubDepartments pubDepartments= PubDepartmentsMapper.selectByPrimaryKey(Doctorlist.get(i).getDepId());
               if (pubDepartments!=null){
                   if (pubDepartments.getDepClinic().equals("1")&&pubDepartments.getStatus().equals("0")){
                       Doctorlist2.add(Doctorlist.get(i));
                   }
               }
           }
        }
        String[] l=new String[Doctorlist2.size()];
        for (int i=0;i<Doctorlist2.size();i++){
            l[i]=Doctorlist2.get(i).getDoctorName();
        }
        System.out.println(Doctorlist2.size());
        Set set=new HashSet();
        List arr=new ArrayList();
        for (int i=0;i<l.length;i++){
            set.add(l[i]);
            arr= Arrays.asList(set.toArray());
        }
        System.out.println(arr.size());
        for (int i=-6;i<=0;i++){
            LocalDate date2= date.plusDays(i);
            for (int k=0;k<arr.size();k++){
                for (int j=0;j<list.size();j++){
                    if (date2.isEqual(ChronoLocalDate.from(list.get(j).getCreateDate()))&&arr.get(k).equals(list.get(j).getDoctorName())){
                        num++;
                    }
                }
                statisdoctor doc=new statisdoctor();
                doc.setDate(date2);
                for (int q=0;q<Doctorlist.size();q++){
                    if (Doctorlist.get(q).getDoctorName()== arr.get(k)){
                        doc.setDocname(Doctorlist.get(q).getDoctorName());
                    }
                }
                doc.setNum(num);
                list1.add(doc);
                num=0;
            }
        }
        return list1;
    }

    @Override
    public List selectStatisDepartments(Map map) {

        List list1=new ArrayList();
        List<OrdAppointment> list=ordAppointmentMapper.selectList(map);
        List<PubDepartments> listDepart= PubDepartmentsMapper.selectList(map);
        List<PubDepartments> listDepart2= new ArrayList<PubDepartments>();
        LocalDate date=LocalDate.now();
        Integer num=0;

        for (int i=0;i<listDepart.size();i++){
            if (listDepart.get(i).getDepClinic().equals("1")&&listDepart.get(i).getStatus().equals("0")){
                listDepart2.add(listDepart.get(i));
            }
        }
        String[] l = new String[listDepart2.size()];
        for (int i=0;i<listDepart2.size();i++){
            l[i]=listDepart2.get(i).getDepName();
        }
        Set set=new HashSet();
        List arr=new ArrayList();
        for (int i=0;i<l.length;i++){
            set.add(l[i]);
            arr= Arrays.asList(set.toArray());
        }

        for (int i=-6;i<=0;i++){
            LocalDate date2= date.plusDays(i);
            for (int k=0;k<arr.size();k++){
                for (int j=0;j<list.size();j++){
                    if (date2.isEqual(ChronoLocalDate.from(list.get(j).getCreateDate()))&&arr.get(k).equals(list.get(j).getDepName())){
                        /*System.out.println(arr.get(k)+"=="+list.get(j).getHospitalId());*/
                        num++;
                    }
                }
                statisdepartments statis2=new statisdepartments();
                statis2.setDate(date2);
                for (int q=0;q<listDepart.size();q++){
                    if (listDepart.get(q).getDepName()== arr.get(k)){
                        statis2.setDepName(listDepart.get(q).getDepName());
                    }
                }
                statis2.setNum(num);
                list1.add(statis2);
                num=0;
            }
        }
        return list1;
    }

    private void AppointmentFunMain(PubHospital hospital, OrdAppointment appointment) throws Exception {
        MainServiceImplPortType service=null ;
        String strResult = "";
        try {
            Document document = DocumentHelper.createDocument();
            Element root = document.addElement("data");
            Element funcode = root.addElement("funcode");
            funcode.setText("200106");
            //1. 医院编号 orgid 32 N单医院接入传空，地市平台接入传医院在地市平台的编号
            Element orgid = root.addElement("orgid");
            orgid.setText(hospital.getHosMarkCode());
            //2. 取号密码 pass 8 N取号密码， 预约时平台传给医院
            Element pass = root.addElement("pass");
            pass.setText(appointment.getPassword());
            //3. 取号代码 takecode 1 N 见取号状态代码
            Element takecode = root.addElement("takecode");
            takecode.setText("1");
            //4. 取号时间 taketime 14 Y YYYYMMDDhhmmss
            Element taketime = root.addElement("taketime");
            taketime.setText("");
            //5. 就诊时间 visittime 14 Y YYYYMMDDhhmmss
            Element visittime = root.addElement("visittime");
            visittime.setText("");
            //6. 医嘱时间 doctime 14 Y YYYYMMDDhhmmss
            Element doctime = root.addElement("doctime");
            doctime.setText("");
            //7. 付费时间 paytime 14 Y YYYYMMDDhhmmss
            Element paytime = root.addElement("paytime");
            paytime.setText("");
            //8. 取药时间 medtime 14 Y YYYYMMDDhhmmss
            Element medtime = root.addElement("medtime");
            medtime.setText("");
            //9. 医保卡类型 cardtype 2 Y 见医保卡类型代码
            Element cardtype = root.addElement("cardtype");
            cardtype.setText("");
            //10. 医保卡号 cardno 32 Y
            Element cardno = root.addElement("cardno");
            cardno.setText("");

            strResult = service.funMain(document.asXML());
            Document documentResult = DocumentHelper.parseText(strResult);
            //获取根节点
            Element rootElt = documentResult.getRootElement();
            //获取根节点名称
            String rootName = rootElt.getName();
            //获取子节点
            Element stateElt = rootElt.element("state");
            Element resultElt = rootElt.element("result");
            if (!stateElt.getTextTrim().equals("0")) {
                throw new Exception(strResult);
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }


    /**
     * HIS预约
     * @param record
     * @return
     * @throws Exception
     */
    private ExecutionResult pushDataHIS(OrdAppointment record) throws Exception {
        //推送预约数据到HIS
        PubHospital hospital = hospitalMapper.selectByPrimaryKey(record.getHospitalId());
        StringBuilder inData =  new StringBuilder();
        //8650696|20181028|0|D95|76183837|2|9903|125.120.179.18|null|null|2018-10-21 17:26:40
        //用户编号 varchar2/10 用户在平台的 ID，患者注册到医院时又平台传给医院
        inData.append(record.getPatId()+"|");
        //就诊日期 Char/8 格式：YYYYMMDD 否
        inData.append(LocalDateTimeUtil.format(record.getVisitDate(), DatePattern.PURE_DATE_PATTERN)+"|");
        //上午/下午 Char/1 0-上午 ；1-下午 否
        inData.append(record.getTimeState().equals(1)?"0":"1").append("|");
        //排班 ID Char/10 用户预约的排班在医院 HIS 系统的排班ID
        OrdScheduling ordScheduling = schedulingMapper.selectByPrimaryKey(record.getSchedulingId());
        inData.append(ordScheduling.getOriginalSchedule()+"|");
        //取号密码 char/8 8 位的取号密码，一周内不可重复，可 0开头，不可字母。
        inData.append(record.getPassword() +"|");
        //预约序号 Char/2 用户预约的就诊序号 否
        inData.append(record.getSerialNumber()+"|");
        //服务商编码 String(4) 否
        inData.append("py"+"|");
        //工号 String(50) 服务商操作人员工号或预约用户 IP 否
        inData.append("127.0.0.1"+"|");
        //预约机构代码 String(10) 是
        inData.append(hospital.getHosMarkCode()+"|");
        //预约机构名称 String(30) 机构名称如 12580、朝辉社区 是
        inData.append(hospital.getHosName()+"|");
        //平台时间 Date YYYY-MM-DD HH:MM:SS例：2017-01-12 08:12:43是
        inData.append(LocalDateTimeUtil.format(LocalDateTime.now(),"yyyy-MM-dd HH:mm:ss"));
        String tokenStr = "";
        try {
            System.out.println(inData.toString());
            tokenStr = HttpUtil.post(hospital.getHosRegionalCode()+"/book/storedProcedure", "inData="+inData.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("第三方接口异常");
        }
        HttpResult httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
        ExecutionResult executionResult = JSONUtil.toBean(JSONUtil.parseObj(httpResult.getData()),ExecutionResult.class);
        return executionResult;
    }



    /**
     * 取消HIS预约
     * @param record
     * @return
     * @throws Exception
     */
    private ExecutionResult deleteDataHIS(OrdAppointment record) throws Exception {
        StringBuilder inData =  new StringBuilder();
        PubHospital hospital = hospitalMapper.selectByPrimaryKey(record.getHospitalId());
        //取消HIS中的预约数据
        //20151122|69514581|3031307
        //就诊日期 Timestamp 格式：YYYYMMDD 否
        inData.append(LocalDateTimeUtil.format(record.getVisitDate(), DatePattern.PURE_DATE_PATTERN)+"|");
        //取号密码 String(8) 8 位的取号密码，一周内不可重复，可 0 否浙江省医院预约诊疗服务系统医院接入规范 第 30 页 开头，不可字母。
        inData.append(record.getPassword()+"|");
        //用户编号 String
        inData.append(record.getPatId().toString());
        String tokenStr = "";
        try {
            tokenStr = HttpUtil.post(hospital.getHosRegionalCode()+"/cancel/storedProcedure", "inData="+inData.toString());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("第三方接口异常");
        }
        HttpResult httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
        ExecutionResult executionResult = JSONUtil.toBean(JSONUtil.parseObj(httpResult.getData()),ExecutionResult.class);
        return executionResult;
    }

    /**
     * 患者信息注册
     * @param sufferer
     * @return
     * @throws Exception
     */
    private ExecutionResult storedProcedure(PubSufferer sufferer) throws Exception {
        //inData=8650696|毛奕能|男|0|330102198411240019|||13738137370||
        Map<String,Object> map = new HashMap<>(7);
        PubHospital hospital = hospitalMapper.selectByPrimaryKey(sufferer.getHospitalId());
        StringBuilder inData =  new StringBuilder();
        //用户编号 varchar2/10 用户在平台的 ID，患者注册到医院时又平台传给医院
        inData.append(sufferer.getId().toString()+"|");
        inData.append(sufferer.getPatName()+"|");
        inData.append(sufferer.getPatSex()+"|");
        inData.append("0|");
        inData.append(sufferer.getPatIdentityNum()+"|");
        inData.append("|");
        inData.append("|");
        inData.append(sufferer.getPatPhone()+"|");
        inData.append("|");
        String tokenStr = "";
        ExecutionResult executionResult ;
        if (Optional.ofNullable(hospital.getHosRegionalCode()).isPresent()){
            try {
                tokenStr = HttpUtil.post(hospital.getHosRegionalCode()+"/register/storedProcedure", "inData="+inData.toString());
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("第三方接口异常");
            }
            HttpResult httpResult = JSONUtil.toBean(JSONUtil.parseObj(tokenStr),HttpResult.class);
            executionResult = JSONUtil.toBean(JSONUtil.parseObj(httpResult.getData()),ExecutionResult.class);
        }else {
            throw new Exception(hospital.getHosName()+"中间服务地址未设置");
        }
        return executionResult;
    }

//    @Override
//    public PageInfo<OrdAppointmentWrapper> selectListWrapperPage(Map<String, Object> map, int pageNum, int pageSize) {
//        PageHelper.startPage(pageNum, pageSize);
//        List<OrdAppointmentWrapper> list = ordAppointmentMapper.selectListWrapper(map);
//        for (OrdAppointmentWrapper ordAppointmentWrapper:list){
//            PubPatients patients = patientsMapper.selectByPrimaryKey(ordAppointmentWrapper.getSufferId());
//            ordAppointmentWrapper.setSufferName(patients.getPatName());
//        }
//        return new PageInfo<OrdAppointmentWrapper>(list);
//    }


    @Override
    public DataCenter selectDataCenter() {
        DateTime startDate = DateUtil.beginOfWeek(DateUtil.date());
        DateTime endDate   = DateUtil.endOfWeek(DateUtil.date());
        Map<String, Object> sMap = new HashMap<>(16);
        sMap.put("startDate",startDate.toDateStr() );
        sMap.put("endDate", endDate.toDateStr());
        List<OrdAppointment> appointments = ordAppointmentMapper.selectList(sMap);
        HashSet<String> hashSet=new HashSet<String>(20);
        DataCenter dataCenter = new DataCenter();
        //总数
        Long appCount=0L;
        for (OrdAppointment app:appointments){

            if (hashSet.contains(app.getSchedulingId().toString())){
                continue;
            }
            System.out.println(LocalDate.now());
            System.out.println(app.getVisitDate());
            System.out.println(LocalDate.now().isAfter(app.getVisitDate()));
            if (LocalDate.now().isAfter(app.getVisitDate())){
                OrdSchedulingHistory  history =schedulingHistoryMapper.selectByPrimaryKey(app.getSchedulingId());
                if (Optional.ofNullable(history).isPresent()){
                    appCount=appCount+history.getAmount();
                }
            }else {
                OrdScheduling  scheduling = schedulingMapper.selectByPrimaryKey(app.getSchedulingId());
                if (Optional.ofNullable(scheduling).isPresent()){
                    appCount=appCount+scheduling.getAmount();
                }
            }
            hashSet.add(app.getSchedulingId().toString());
        }
        dataCenter.setTotal(appCount);
        //总预约数
        dataCenter.setAppTotal(appointments.stream().count());
        //省平台
        dataCenter.setProvince(appointments.stream().filter(ordAppointment -> ordAppointment.getSpName().equals("12580")).count());
        //诊间预约
        dataCenter.setOffice(appointments.stream().filter(ordAppointment -> ordAppointment.getSpName().equals("诊间预约")).count());
        //电话预约
        dataCenter.setPhone(appointments.stream().filter(ordAppointment -> ordAppointment.getSpName().equals("电话预约")).count());
        //H5
        dataCenter.setWeb(dataCenter.getAppTotal() - dataCenter.getOffice() - dataCenter.getPhone() - dataCenter.getProvince());

        //分管记录
        //上周总数
        //上周预约总数
        //本周实时预约总数
//        dataCenter.setFtZoneDataCenter(zoneDataCenterCount(57170L));
//        dataCenter.setFqZoneDataCenter(zoneDataCenterCount(57171L));
//        dataCenter.setHpZoneDataCenter(zoneDataCenterCount(57172L));
        return dataCenter;
    }

    @Override
    public ZoneDataCenter selectZoneDataCenterCount(Long hospitalId){
        ZoneDataCenter zoneDataCenter = new ZoneDataCenter();
        DateTime startDate = DateUtil.beginOfWeek(DateUtil.date());
        DateTime endDate   = DateUtil.endOfWeek(DateUtil.date());
        DateTime beforeStartDate = DateUtil.beginOfWeek(DateUtil.lastWeek());
        DateTime beforeEndDate   = DateUtil.endOfWeek(DateUtil.lastWeek());

        Map<String, Object> sMap = new HashMap<>(16);
        sMap.put("startDate", beforeStartDate.toDateStr());
        sMap.put("endDate", beforeEndDate.toDateStr());
        sMap.put("hospitalId", hospitalId);

        Long appCount=0L;
        List<OrdAppointment> appointments = ordAppointmentMapper.selectList(sMap);
        HashSet<String> hashSet=new HashSet<String>(20);
        for (OrdAppointment app:appointments){
            System.out.println(LocalDate.now());
            System.out.println(app.getVisitDate());
            System.out.println(LocalDate.now().isAfter(app.getVisitDate()));
            if (hashSet.contains(app.getSchedulingId().toString())){
                continue;
            }
            if (LocalDate.now().isAfter(app.getVisitDate())){
                OrdSchedulingHistory  history =schedulingHistoryMapper.selectByPrimaryKey(app.getSchedulingId());
                if (Optional.ofNullable(history).isPresent()){
                    appCount=appCount+history.getAmount();
                }
            }else {
                OrdScheduling  scheduling = schedulingMapper.selectByPrimaryKey(app.getSchedulingId());
                if (Optional.ofNullable(scheduling).isPresent()){
                    appCount=appCount+scheduling.getAmount();
                }
            }
            hashSet.add(app.getSchedulingId().toString());
        }
        zoneDataCenter.setBeforeWeekCount(appCount);
        zoneDataCenter.setBeforeWeekAppCount(appointments.stream().count());

        sMap.put("startDate", startDate.toDateStr());
        sMap.put("endDate", endDate.toDateStr());
        sMap.put("hospitalId", hospitalId);

        appCount=0L;
        appointments = ordAppointmentMapper.selectList(sMap);
        hashSet=new HashSet<String>(20);
        for (OrdAppointment app:appointments){
            System.out.println(LocalDate.now());
            System.out.println(app.getVisitDate());
            System.out.println(LocalDate.now().isAfter(app.getVisitDate()));
            if (hashSet.contains(app.getSchedulingId().toString())){
                continue;
            }
            if (LocalDate.now().isAfter(app.getVisitDate())){
                OrdSchedulingHistory  history =schedulingHistoryMapper.selectByPrimaryKey(app.getSchedulingId());
                if (Optional.ofNullable(history).isPresent()){
                    appCount=appCount+history.getAmount();
                }
            }else {
                OrdScheduling  scheduling = schedulingMapper.selectByPrimaryKey(app.getSchedulingId());
                if (Optional.ofNullable(scheduling).isPresent()){
                    appCount=appCount+scheduling.getAmount();
                }
            }
            hashSet.add(app.getSchedulingId().toString());
        }

        zoneDataCenter.setCurrentWeekCount(appCount);
        zoneDataCenter.setCurrentWeekAppCount(appointments.stream().count());

        return zoneDataCenter;
    }



}
